﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;

#if !SILVERLIGHT
namespace UIT.WPF.Renderers
#else
namespace UIT.Silverlight.Renderers
#endif
{
#if !SILVERLIGHT
    class StackPanelRenderer :
        WpfRenderer<Controls.Containers.StackPanel, StackPanel>
#else
    public class StackPanelRenderer :
        SlRenderer<Controls.Containers.StackPanel, StackPanel>
#endif
    {
        public override void Render(Controls.Containers.StackPanel control)
        {
            Result = new StackPanel();
            Result.Orientation = (Orientation)(int)control.Orientation;
            control.Children.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Children_CollectionChanged);
            foreach (var item in control.Children)
            {
                var childUI = Manager.Render(item);
                if (childUI != null)
                    Result.Children.Add(childUI);
            }
        }

        void Children_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
                case System.Collections.Specialized.NotifyCollectionChangedAction.Add:
                    foreach (Controls.IControl item in e.NewItems)
                    {
                        var childUI = Manager.Render(item);
                        if (childUI != null)
                            Result.Children.Add(childUI);
                    }
                    break;
#if !SILVERLIGHT
                case System.Collections.Specialized.NotifyCollectionChangedAction.Move:
                    break;
#endif
                case System.Collections.Specialized.NotifyCollectionChangedAction.Remove:
                    foreach (var childUI in Result.Children.Cast<System.Windows.FrameworkElement>().Where(fe => e.OldItems.Contains(fe.DataContext)))
                    {
                        Result.Children.Remove(childUI);
                    }
                    break;
                case System.Collections.Specialized.NotifyCollectionChangedAction.Replace:
                    break;
                case System.Collections.Specialized.NotifyCollectionChangedAction.Reset:
                    Result.Children.Clear();
                    break;
                default:
                    break;
            }
        }
    }
}
